package com.ayu.scalalearn.chapter08

/**
  * @Author 徐林玉
  * @Description Test06PartialFunction
  * @Date 2022/8/26 10:45
  * @Version 1.0
  */
object Test06PartialFunction {

  def main(args: Array[String]): Unit = {

    val list: List[(String, Int)] = List(("a", 12), ("b", 35), ("c", 27), ("a", 13))


    //1、map转换 ， key不变 value变成两倍
    val newList = list.map(elem => (elem._1, elem._2 * 2))


    //2、用模式匹配对元素复制实现功能
    val newList2 = list.map(elem => {

      elem match {

        case (a, b) => (a, b * 2)
      }

    })


    //2、省略lambda表达式的写法,进行简化
    val newList3 = list.map{ case (a, b) => (a, b * 2) }


    println(newList)
    println(newList2)
    println(newList3)

    // 偏函数的应用，求绝对值
    // 对输入数据分为不同的情形：正、负、0
    val positiveAbs: PartialFunction[Int, Int] = {
      case x if x > 0 => x
    }
    val negativeAbs: PartialFunction[Int, Int] = {
      case x if x < 0 => -x
    }
    val zeroAbs: PartialFunction[Int, Int] = {
      case 0 => 0
    }

    def abs(x: Int): Int = (positiveAbs orElse negativeAbs orElse zeroAbs) (x)

    println(abs(-67))
    println(abs(35))
    println(abs(0))
  }


}
